<?php

namespace Frieza\Modules\Point\Controllers;

use App\Admin\Extensions\Tools\UserButton;
use App\Exceptions\InputErrorException;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Member;
use Doraemon\model\Point\SystemPoint as mSystemPoint;
use Doraemon\model\Point\SystemPointUser as mSystemPointUser;
use Doraemon\pockets\excel\DownExcel;
use Doraemon\service\Point\SystemPoint as sSystemPoint;
use Doraemon\service\Point\SystemPointUser as sSystemPointUser;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class PointController
{
    public function index(Content $content, Request $request)
    {
        $params = $request->all();
        $where = $this->buildWhere($params);
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 20);
        $limit = [($page - 1) * $pageSize, $pageSize];
        $list = sSystemPoint::getList($where, $limit);
        $gridModel = new pGridDataModel($list['list'], $list['total'], [
            'perPage' => $pageSize,
        ]);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($where) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->expandFilter();

            $grid->tools(function (Grid\Tools $tool) use ($where) {
                $tool->append(new UserButton(UserButton::TYPE_HREF, 'add/0', '新增'));
                $href = '/admin/point/down-excel?condition=' . base64_encode(json_encode($where));
                $tool->append("<a href={$href} class='btn button-success' ><i class='fa fa-file-excel-o'></i>>导出</a>");
            });

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->expand();
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('uid', '用户Id');
                });
                $filter->column(1 / 2, function ($filter) {
                    $filter->between('add_time', '下发时间')->datetime();
                });
            });

            $grid->column('id', '项目ID');
            $grid->column('admin_id', '操作人')->display(function () {
                return Admin::user()->find($this->admin_id)->name;
            });
            $grid->column('total_point', '发放总积分数');
            $grid->column('point', '单人被送积分');
            $grid->column('total_user', '被发放人数');
//            $grid->column('remark', '备注')->display(function () {
//                if (mb_strlen($this->remark) > 50) {
//                    return mb_substr($this->remark, 0, 50) . '...';
//                }
//                return $this->remark;
//            });
            $grid->column('content', '下发原因')->display(function () {
                if (mb_strlen($this->content) > 50) {
                    return mb_substr($this->content, 0, 50) . '...';
                }
                return $this->content;
            });
            $grid->column('department', '部门')->width(100);
            $grid->column('add_time', '下发时间')->display(function () {
                return date('Y-m-d H:i:s', $this->add_time);
            });
            $grid->column('status', '发放状态')->display(function () {
                return mSystemPoint::STATUS_MAP[$this->status];
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableDelete();
                $actions->disableEdit();
                $actions->append('<a href="/admin/point/add/' . $actions->row->id . '"  class="fa fa-eye" style="margin-right: 10px">查看详情</a>');
                $actions->append('<a href="/admin/point/user/' . $actions->row->id . '"  class="fa fa-user-plus">发放详情</a>');
            });
        });
        return $content
            ->header('用户管理 积分发放')
            ->breadcrumb(['text' => '用户管理 积分发放', 'url' => ''])
            ->body($listGrid);
    }

    public function buildWhere($param)
    {
        $where = [];
        if (isset($param['uid']) && $param['uid'] !== '') {
            $sId = mSystemPointUser::getSidByUid($param['uid']);
            $where['id'] = $sId ?: [0];
        }
        if (!empty($param['add_time'])) {
            $addTime = $param['add_time'];
            if ($addTime['start'] && $addTime['end']) {
                $where['AND']['add_time[<>]'] = [strtotime($addTime['start']), strtotime($addTime['end'])];
            }
        }
        return $where;
    }

    //创建
    public function add(Request $request, Content $content, $id = 0)
    {
        Admin::script($this->sub());
        Admin::script($this->setScript());
        $info = [];
        if ($id) {
            $info = sSystemPoint::getDetail($id);
        }
        $form = new Form($info);
        $uid = $form->textarea('uid', '用户UID')->help('英文逗号隔开')->required();
        $point = $form->text('point', '单人发放积分数')->default(1)->Width(10)->required();
        $form->html('<span id="point_limit" class="help-block" style="color:#cd112e;display: none;margin-top: 1px"><i class="fa fa-info-circle" >数目过大，请慎重填写</i></span>');
        $remark = $form->textarea('remark', '备注');
        $contents = $form->textarea('content', '下发原因')->required();
        $information = $form->textarea('information', '系统消息')->required();
        $department = $form->text('department', '部门')->help("添加积分申请人请按照此格式：部门名称,申请人名称");
        if ($id) {
            $form->text('total_point', '发放总积分')->default($info['total_point'])->readonly();
            $form->text('admin_ids', '操作人')->default(Admin::user()->find($info['admin_id'])->name)->readonly();
            $uid->readonly();
            $point->readonly();
            $remark->readonly();
            $contents->readonly();
            $information->readonly();
            $department->readonly();
        } else {
            $form->html('<div style="text-align:center;padding-top: 40px" >
                    <button class="btn btn-sm btn-success button-1134271147" type="submit" id="goods_save" value="保存" style="margin-right: 100px;width: 100px;height: 40px">提交</button></div>');
        }
        $form->disableSubmit();
        $form->disableReset();
        $form->action(url('admin/point/save'));
        return $content->header('用户管理')->breadcrumb(['text' => '积分下发', 'url' => url('')])
            ->row($form->render());
    }

    public function sub()
    {
        return <<<SCRIPT
        $('#goods_save').unbind('click').click(function(){
            var point = $("#point").val();
            var uid = $(".uid").val();
            var arr = [];
            arr = uid.split(',')
            var sumPoint = parseInt(arr.length) * parseInt(point)
            if(confirm('以下'+arr.length+'位用户，将会下发 '+sumPoint+' 积分，请确认名单!'))
            {
                return true;
            }
            return false;
         });
SCRIPT;
    }

    public function setScript()
    {
        return <<<SCRIPT
			var os = document.getElementById('point');
			//内容改变事件
			os.onchange = function(){
			console.log(1)
			    var point = $("#point").val();
			    var btn = document.getElementById('point_limit');
			    if(point >=10000){
                    btn.style.display = "block";
			    }else{
			        btn.style.display = "none";
			    }
			};
SCRIPT;
    }

    public function save(Request $request)
    {
        $params = $request->all();
        Log::info('系统发放积分记录提交的信息', $params);
        $uidStr = str_replace(array("\r\n", "\r", "\n", " "), "", str_replace('，', ',', $params['uid']));
        $uid = explode(',', $uidStr);
        //uid数量限制
        if (count($uid) > 100) {
            throw new InputErrorException("人数过多，无法提交", InputErrorException::DEFAULT_CODE, 'uid');
        }
        //uid重复性提示
        $unUid = array_count_values($uid);
        foreach ($unUid as $key => $val) {
            if ($val > 1) {
                throw new InputErrorException("UID：{$key}重复", InputErrorException::DEFAULT_CODE, 'uid');
            }
        }
        $userCount = Member::getUserList($uid);
        //查询uid有效性
        if ($userCount != count($uid)) {
            $diffUid = array_diff($uid, array_keys($userCount));
            if ($diffUid) {
                $diffUid = implode(',', $diffUid);
                throw new InputErrorException("UID：{$diffUid}无效", InputErrorException::DEFAULT_CODE, 'uid');
            }
        }
        //积分的限制
        if (!ctype_digit($params['point']) || $params['point'] < 0) {
            throw new InputErrorException("请填写正确格式的积分数", InputErrorException::DEFAULT_CODE, 'point');
        }
        //备注限制100以内
        if (mb_strlen($params['remark']) > 100) {
            throw new InputErrorException("备注限制在100字以内", InputErrorException::DEFAULT_CODE, 'remark');
        }

        $data['point'] = $params['point'];
        $data['remark'] = $params['remark'];
        $data['content'] = $params['content'];
        $data['information'] = $params['information'];
        $data['admin_id'] = Admin::user()->id;
        $data['admin_name'] = Admin::user()->name;
        $data['total_user'] = count($uid);
        $data['total_point'] = count($uid) * $params['point'];
        $data['department'] = $params['department'];

        $result = sSystemPoint::save($uid, $data);
        if (empty($result)) {
            $error = new MessageBag([
                'title' => '保存失败，请重试2'
            ]);
            return back()->with(compact('error'))->withInput();
        }
        $success = new MessageBag([
            'title' => "创建成功"
        ]);
        return redirect("/admin/point")->with(compact('success'));
    }

    //发放详情
    public function giveDetail(Content $content, Request $request, $id)
    {
        $params = $request->all();
        $where = ['s_id' => $id];
        if (isset($params['uid']) && $params['uid'] !== '') {
            $where['uid'] = $params['uid'];
        }
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 20);
        $limit = [($page - 1) * $pageSize, $pageSize];
        $list = sSystemPointUser::getList($where, $limit);

        $gridModel = new pGridDataModel($list['list'], $list['total'], [
            'perPage' => $pageSize,
        ]);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->expandFilter();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->expand();
                $filter->column(1/2, function ($filter) {
                    $filter->equal('uid', '用户Id');
                });
            });

            $grid->column('uid', '用户uid');
            $grid->column('nick', '用户名称');
            $grid->column('point', '积分数');
            $grid->column('upd_time', '操作时间')->display(function () {
                if ($this->upd_time) {
                    return date('Y-m-d H:i:s', $this->upd_time);
                }
            });
            $grid->column('status', '发放状态')->display(function () {
                return mSystemPointUser::STATUS_MAP[$this->status];
            });
            $grid->disableActions();
        });
        return $content
            ->header('积分发放 发放状态')
            ->breadcrumb(['text' => '积分发放 发放状态', 'url' => ''])
            ->body($listGrid);
    }

    public function downExcel(Request $request)
    {
        $params = $request->all();
        $where = $params['condition'];
        $where = json_decode(base64_decode($where), 1);
        $where['ORDER'] = ['id' => 'DESC'];
        $data = mSystemPoint::getList($where);
        if (empty($data)) {
            $error = new MessageBag(['title' => '导出失败，该期间暂无数据']);
            return back()->with(compact('error'))->withInput();
        }
        $list = [];
        foreach ($data as $val) {
            $department = explode(',', $val['department']);
            $list[] = [
                $val['id'],
                'id:' . $val['staff_id'] . ' 用户名:' . Admin::user()->find($val['admin_id'])->name,
                $val['total_point'],
                $val['point'],
                $val['total_user'],
                $val['content'],
                date('Y-m-d H:i:s', $val['add_time']),
                mSystemPoint::STATUS_MAP[$val['status']],
                $department[0] ?? '',
                $department[1] ?? '',
            ];
        }
        $downExcel = new DownExcel();
        $letter = range('A', 'J');
        $widths = [
            'A' => 8, 'B' => 12, 'C' => 8, 'D' => 8, 'E' => 8,
            'F' => 20, 'G' => 20, 'H' => 10, 'I' => 10, 'J' => 10
        ];
        $title = '统计信息导出';
        $downExcel->setFrontBold('1');
        $downExcel->setWidth($widths);
        $downExcel->setFileName($title);
        $downExcel->setTitle($title);
        $downExcel->setSheetTitle($title);

        $header = [
            '项目ID', '操作人', '发放总积分数', '单人被送积分', '被发放人数',
            '下发原因', '下发时间', '发放状态', '部门', '积分申请人'
        ];

        foreach ($header as $key => $value) {
            //设置字体
            $downExcel->setFrontName($letter[$key]);
            //设置大小
            $downExcel->setFrontSize($letter[$key]);
        }

        $downExcel->create($list, $header);
        return back();
    }
}